import random
import hashlib
import time
from blog import settings
from passlib.context import CryptContext

try:
    random = random.SystemRandom()
    using_sysrandom = True
except NotImplementedError:
    using_sysrandom = False

def gen_secret_key(length:int=12,
                      allowed_chars:str='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')->str:
    if not using_sysrandom:
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
            ).digest()
        )
    return ''.join(random.choice(allowed_chars) for i in range(length))

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def gen_token(username:str, password:str)->str:
    return pwd_context.hash(username+settings.SECRET_KEY+password)

def verify_token(token:str):
    try:
        return pwd_context.verify(settings.ADMIN_USERNAME+settings.SECRET_KEY+settings.ADMIN_PASSWORD, token)
    except ValueError:
        return False